package com.su.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.BeanUtils;

import com.su.gulimall.product.service.CategoryBrandRelationService;
import com.su.gulimall.product.vo.Catelog2Vo;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.su.common.utils.PageUtils;
import com.su.common.utils.Query;

import com.su.gulimall.product.dao.CategoryDao;
import com.su.gulimall.product.entity.CategoryEntity;
import com.su.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redissonClient;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }
    //查询所有的对象，
    @Override
    public List<CategoryEntity> listWithTree() {
        //第一步，查出所有分类，
        List<CategoryEntity> entityList = baseMapper.selectList(null);
        //将分类进行组装，筛选为一级分类，二级分类和三级分类
        //找到对应的一级分类；（父分类id为0）
        List<CategoryEntity> categoryEntityList = entityList.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0)
                .map((menu) -> {
                    menu.setChildren(getChildrens(menu, entityList));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());
        return categoryEntityList;
    }
    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream().filter(categoryEntity ->
                //当前实体类id和传入的root实体类的子id进行比较，如果相等，
                categoryEntity.getParentCid().longValue() == root.getCatId().longValue())
                .map(categoryEntity -> {
                    //1、找到子菜单的子元素
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                }).sorted((menu1, menu2) -> {
                    //2、菜单的排序
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                }).collect(Collectors.toList());
        return children;
    }
    //删除
    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO 检查当前删除的菜单，是否被其他地方引用
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        ArrayList<Long> paths = new ArrayList<>();
        List<Long> allPaths = findParent(catelogId, paths);
        Collections.reverse(allPaths);
        //集合转为数组的方法
        return allPaths.toArray(new Long[allPaths.size()]);
    }

    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        //自己更新
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            //冗余字段也要更新,创建相关sql,根据id，同步修改name
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }

    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        List<CategoryEntity> entityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
        return entityList;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJsonWithRedisson() {
        //第一步，获取分布式锁，限制查询数据库的线程只有一个；此时锁的粒度越细，并发效果更好
        RLock lock = redissonClient.getLock("catalogJson");
        //第二步，锁住业务代码；没有设置锁的过期时间，默认触发看门狗机制
        lock.lock();
        System.out.println("获取分布式锁成功,当前线程id为" + Thread.currentThread().getId());
        Map<String, List<Catelog2Vo>> dataFromDb = null;
        try {
            //此处为数据库的查询操作，并且包含了redis的查询成功放进数据库
            dataFromDb = getCatalogJsonFromDb();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("查询数据库出现了未知错误，请查看控制台寻找原因");
        } finally {
            //第三步，业务执行完成，自动解锁
            lock.unlock();
            System.out.println("删除分布式锁成功,当前线程id为" + Thread.currentThread().getId());
        }
        return dataFromDb;
    }

    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {

        //为redis数据库查询做准备
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String catalogJSON = ops.get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            System.out.println("缓存不命中，正在查询数据库");
            Map<String, List<Catelog2Vo>> fromDb = getCatalogJsonWithRedisson();
            //此处的返回直接返回至controller，进行页面的显示
            return fromDb;
        }
        //如果不为空，直接在缓存中拿数据
        System.out.println("缓存命中，直接在redis中拿数据");
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    //从数据库查询并封装分类数据
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDb() {
        //为减少数据库的交互，进行业务优化
        //查询出所有的分类信息
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //找到所有的一级分类
        List<CategoryEntity> categoryEntityList = getParent_cid(selectList, 0L);
        //对一级分类进行封装成一个map
        Map<String, List<Catelog2Vo>> parent_cid = categoryEntityList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //此时拿到的是一级分类。每一个一级分类下有多个二级分类，且二级分类下有多个三级分类，
            //需要根据该一级分类id,查询出来所有值，备好；
            List<CategoryEntity> entityList = getParent_cid(selectList, v.getCatId());
            List<Catelog2Vo> catelog2VoList = null;
            if (entityList != null) {
                catelog2VoList = entityList.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    List<CategoryEntity> level3Catelog = getParent_cid(selectList, l2.getCatId());
                    if (level3Catelog != null) {
                        //封装成相应的3级分类
                        List<Catelog2Vo.Catelog3Vo> collect = level3Catelog.stream().map(l3 -> {
                            Catelog2Vo.Catelog3Vo catelog3Vo = new Catelog2Vo.Catelog3Vo
                                    (l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catelog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2VoList;
        }));
        //缓存中存储json字符串：跨语言，跨平台兼容,将其与数据库查询操作放在一起
        String s = JSON.toJSONString(parent_cid);
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        ops.set("catalogJSON", s);
        //将从数据库查询到的数据返回
        return parent_cid;
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }

    private List<Long> findParent(Long catelogId, ArrayList<Long> paths) {
        //第一步，收集当前id
        paths.add(catelogId);
        //第二步，根据id获得其实体类信息，并判断其是否具有父节点
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParent(byId.getParentCid(), paths);
        }
        return paths;
    }

}